package com.mxprojects.admin
{
	import com.mxprojects.constructors.ButtonConstructor;
	import com.mxprojects.gui.DefaultDialog;
	import com.mxprojects.io.BoardCookie;
	import com.mxprojects.io.CustomEvent;
	import com.mxprojects.io.DeepLinking;
	import com.mxprojects.io.ServerHandler;
	import com.mxprojects.language.Language;
	import com.mxprojects.language.Word;

	public class AdminHandleData
	{
		private var onSuccess:Function;
		private var actionButton:ButtonConstructor;
		
		public function AdminHandleData(dataToSend:Object, onSuccess:Function, actionButton:ButtonConstructor, adminScript:String){
			//disable the button
			if(actionButton != null){
				actionButton.enabled = false;
			}
			
			//this will handle sending stuff to the server within the admin FRONT END
			dataToSend.username = BoardCookie.getUser();
			dataToSend.password = BoardCookie.getPassword();
			
			//set the private vars
			this.onSuccess = onSuccess;
			this.actionButton = actionButton;
			
			//send off the data
			var serverHandler:ServerHandler = new ServerHandler();
			serverHandler.transmitData(adminScript, dataToSend);
			serverHandler.listenForData(handleData);
		}
		
		private function handleData(event:CustomEvent):void {
			//handle the stuff that comes back from the server
			var data:Object = event.getServerData();
			
			switch(data.output){
				case "badLogin":
					DefaultDialog.show(Language.main(Word.ERROR_LOGIN_INVALID));
				break;
				
				case "mySqlError":
					DefaultDialog.show(Language.main(Word.ERROR_MYSQL) + "\n\n" + data.error);
				break;
				
				case "permissionError":
					//if they are not allowed to be here, send them back to the main forums
					DefaultDialog.show(Language.main(Word.ERROR_PERMISSION_DENIED), true, Word.ERROR, loadForums);
				break;
				
				default:
					//handle the success
					onSuccess.call(null, event);
				break;
			}
			
			//enable the button
			if(actionButton != null){
				actionButton.enabled = true;
			}
		}
		
		private function loadForums():void {
			//a simple function to send them back to the main page
			DeepLinking.setLink(Word.FORUMS, DeepLinking.createLinkArray());
		}
	}
}